package com.szosen.application;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.example.test.MainActivity;
import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.fs.UsbFileInputStream;
import com.github.mjdev.libaums.partition.Partition;
import com.lzy.okgo.OkGo;
import com.sinocare.bluetoothle.SN_BluetoothLeConnection;
import com.szosen.jkzj.R;
import com.szosen.json.database.JSONDBService;
import com.szosen.util.Cache;
import com.szosen.util.FileSaveUtil;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.Tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyApplication extends MultiDexApplication {
	private static boolean isConnected = false;
	private static MyApplication mInstance = null;
	private static String userName = "";
	private static String password = "";
	private static Cache mCache;
	private Context mContext;
	private static boolean isMountSDCard = false;
	public static final String ACTION_USB_PERMISSION = "com.szosen.jkzj.USB_PERMISSION";
	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}
	public class UsbStatesReceiver extends BroadcastReceiver {
		public static final int USB_STATE_MSG = 0x00020;
		public static final int USB_STATE_OFF = 0x00022;
		Context context = null;

		public UsbStatesReceiver(Context context) {
			this.context = context;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)
					|| intent.getAction().equals(Intent.ACTION_MEDIA_CHECKING)) {
				isMountSDCard = true;
			} else if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)
					|| intent.getAction().equals(Intent.ACTION_MEDIA_REMOVED)) {
				isMountSDCard = false;
			}
			String path = intent.getDataString();
			if (!TextUtils.isEmpty(path)) {
				String pathString = path.split("file://")[1];
				File otgFile = new File(pathString);
				if (otgFile.exists()) {
					File[] files = otgFile.listFiles();
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < files.length; i++) {
						sb.append(files[i].getAbsolutePath() + "\n");
					}
					// ToastTool.showLong(mContext, sb.toString());
				}
			}
			// ToastTool.showLong(mContext, intent.getDataString());
		};
	}

	private void getAllFiles(File path) {
		File files[] = path.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {
					getAllFiles(f);
				} else {
					System.out.println(f);
				}
			}
		}
	}

	private static String otgPath = "";

	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = MyApplication.this;
		mContext = getApplicationContext();
		writeYaowulists();
		int sdk = Build.VERSION.SDK_INT;
		if (sdk >= 18) {
			SN_BluetoothLeConnection BleConnection = SN_BluetoothLeConnection.getBlueToothBleConnection(this);
			BleConnection.initBleApplicationService();
		}
		JSONDBService.getInstance(mContext);
		// registerSDReceiver();
		registerReceiver();
		// 必须调用初始化
		OkGo.init(this);
		OkGo.getInstance().setReadTimeOut(10000L).setConnectTimeout(50000L)
				.setRetryCount(1);
		// sn序列号
		// mac wlan
		// mac 蓝牙
		// psd 密码
		// 储存 .bin
		// 0x55
		// int result=MainActivity.checkid("12345", "12345", "55555");
		// System.out.println("application="+result);
		// System.loadLibrary("jni");
		// String sn = new String("12322");
		// String mac = new String("12333");
		// String pas = new String("12344");
		// System.out.println(sn.hashCode() + "," + sn.toString() + ","
		// + mac.hashCode() + "," + mac.toString() + "," + pas.toString());
		// int result2 = CheckTool.checkid(sn, mac, pas);
		// System.out.println("application计算/result2=" + result2);
		// System.out.println(sn.hashCode() + "," + sn.toString() + ","
		// + mac.hashCode() + "," + mac.toString() + "," + pas.toString());
		/*
		 * WifiManager wifiManager = (WifiManager) this
		 * .getSystemService(Context.WIFI_SERVICE); if
		 * (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); }
		 */
		// Tools.getWlanMacAddress();
	}

	/***
	 * 从本地获取是否注册成功
	 *
	 * @return
	 */
	public static boolean isRegisterAppFromSD() {
		boolean result = false;
		String sn = Tools.getSerialNumber();
		String btAddress = Tools.getBTAddress(mInstance);
		// 从文件中获取秘钥
		String miyao = Tools.readMiyaoContent();
		int check = MainActivity.checkid(sn, btAddress, miyao);
		if (check == 0x55) {
			result = true;
		}
		return result;
	}

	public static boolean isRegisterApp(String sn, String btAddress) {
		boolean result = false;
		// 从文件中获取秘钥
		String miyao = Tools.readMiyaoContent();
		int check = MainActivity.checkid(sn, btAddress, miyao);
		if (check == 0x55) {
			result = true;
		}
		return result;
	}

	/***
	 * 校验两个码是不是ok的。
	 *
	 * @param sn
	 * @param btAddress
	 * @param miyao
	 * @return
	 */
	public static boolean isCheckRegisterAppOk(String sn, String btAddress,
			String miyao) {
		boolean result = false;
		// 从文件中获取秘钥
		int check = MainActivity.checkid(sn, btAddress, miyao);
		if (check == 0x55) {
			result = true;
		}
		return result;
	}

	public static boolean saveMiyao(String miyao) {
		Tools.saveMiYao2SD(miyao);
		return true;
	}

	private void registerSDReceiver() {
		UsbStatesReceiver receiver = new UsbStatesReceiver(mInstance);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_MEDIA_CHECKING);
		filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		filter.addAction(Intent.ACTION_MEDIA_EJECT);
		filter.addAction(Intent.ACTION_MEDIA_REMOVED);
		filter.addDataScheme("file");
		registerReceiver(receiver, filter);
	}

	private void registerReceiver() {
		// 监听otg插入 拔出
		IntentFilter usbDeviceStateFilter = new IntentFilter();
		usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		registerReceiver(mUsbReceiver, usbDeviceStateFilter);
		// 注册监听自定义广播
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		registerReceiver(mUsbReceiver, filter);
		executorService = Executors.newCachedThreadPool();// 30大小的线程池
	}

	private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			switch (action) {
			case ACTION_USB_PERMISSION:
				UsbDevice usbDevice = intent
						.getParcelableExtra(UsbManager.EXTRA_DEVICE);
				if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,
						false)) {
					int vId = usbDevice.getVendorId();
					if (usbDevice != null && vId != 1027) {
						readDevice(getUsbMass(usbDevice));
					}
				}
				break;
			case UsbManager.ACTION_USB_DEVICE_ATTACHED:
				UsbDevice device_add = intent
						.getParcelableExtra(UsbManager.EXTRA_DEVICE);
				int vId = device_add.getVendorId();
				int pId = device_add.getProductId();
				System.out.println("插入了U盘vId=" + vId + "pId=" + pId);
				if (device_add != null && vId != 1027) {
					redDeviceList();
				}
				break;
			case UsbManager.ACTION_USB_DEVICE_DETACHED:
				// UsbDevice device_remove = intent
				// .getParcelableExtra(UsbManager.EXTRA_DEVICE);
				try {
					if (!TextUtils.isEmpty(updateJianhuyi_FilePath)) {
						final File f = new File(updateJianhuyi_FilePath);
						if (f.exists()) {
							f.delete();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
		};
	};

	private UsbMassStorageDevice[] storageDevices;

	private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
		for (UsbMassStorageDevice device : storageDevices) {
			if (usbDevice.equals(device.getUsbDevice())) {
				return device;
			}
		}
		return null;
	}

	private void redDeviceList() {
		UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
		System.out.println("usb设备storageDevices长度：" + storageDevices.length);
		for (UsbMassStorageDevice device : storageDevices) {
			System.out.println("usb设备名称getDeviceName："
					+ device.getUsbDevice().getDeviceName());
			if (device.getUsbDevice().getVendorId() != 1027
					&& device.getUsbDevice().getVendorId() != 4817
					&& device.getUsbDevice().getProductId() != 24577) {
				if (usbManager.hasPermission(device.getUsbDevice())) {
					readDevice(device);
				} else {
					PendingIntent pendingIntent = PendingIntent.getBroadcast(
							this, 0, new Intent(ACTION_USB_PERMISSION), 0);
					usbManager.requestPermission(device.getUsbDevice(),
							pendingIntent);
				}
			}
		}
	}

	private void readDevice(UsbMassStorageDevice device) {
		// before interacting with a device you need to call init()!
		try {
			device.init();
			// Only uses the first partition on the device
			Partition partition = device.getPartitions().get(0);
			FileSystem currentFs = partition.getFileSystem();
			// fileSystem.getVolumeLabel()
			// Log.d(TAG, "Capacity: " + currentFs.getCapacity());
			// Log.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());
			// Log.d(TAG, "Free Space: " + currentFs.getFreeSpace());
			// Log.d(TAG, "Chunk size: " + currentFs.getChunkSize());
			UsbFile root = currentFs.getRootDirectory();// 获取根目录
			String deviceName = currentFs.getVolumeLabel();// 获取设备标签
			mUsbFile = root;
			addFile2List(deviceName);// 添加文件
		} catch (Exception e) {
			e.printStackTrace();
			// ToastTool.showLong(mInstance,"出错了"+e.getMessage());
			FileSaveUtil.saveTxtFile("error", "log.txt", e.getMessage());
		}
	}

	UsbFile mUsbFile;
	private List<UsbFile> usbFiles = new ArrayList<UsbFile>();

	private void addFile2List(String deviceName) {// 添加文件和文件夹到gridView显示
		try {
			StringBuilder sb = new StringBuilder();
			for (UsbFile file : mUsbFile.listFiles()) {
				usbFiles.add(file);
				sb.append(file.getName() + "\n");
				String name = file.getName();
				if (!TextUtils.isEmpty(name) && name.equals("ASUPD")) {
					// UsbFile ub = file.createFile("ASUPD.AS");
					for (UsbFile fileSon : file.listFiles()) {
						String name2 = fileSon.getName();
						if (!TextUtils.isEmpty(name2)
								&& name2.equals("ASUPD.AS")) {
							readFile(fileSon);
							break;
						}
					}
				}
			}
			// ToastTool.showLong(mInstance,
			// "usbFiles.size="+usbFiles.size()+",名字="+usbFiles.get(0).getName()+"\n"+sb.toString());
			// Collections.sort(usbFiles, new Comparator<UsbFile>() {// 简单排序
			// 文件夹在前
			// // 文件在后
			// @Override
			// public int compare(UsbFile oFile1, UsbFile oFile2) {
			// if (oFile1.isDirectory())
			// return -1;
			// else
			// return 1;
			// }
			// });
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String updateJianhuyi_FilePath = "";
	private ExecutorService executorService;

	private void readFile(final UsbFile uFile) {
		String sdPath = FileSaveUtil.getSDCardPath();// 获取sd根目录 创建一个同名文件
		String filePath = sdPath + uFile.getName();
		updateJianhuyi_FilePath = filePath;
		final File f = new File(filePath);
		// if (f.exists()) {
		//
		// } else {
		try {
			f.createNewFile();
			// 设置视图
			// 执行线程
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					try {
						FileOutputStream os = new FileOutputStream(f);
						InputStream is = new UsbFileInputStream(uFile);
						redFileStream(os, is);
					} catch (final Exception e) {
						e.printStackTrace();
						FileSaveUtil.saveTxtFile("dd",
								"executorServicelog.txt", e.getMessage());
					}
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		// }
	}

	private void redFileStream(OutputStream os, InputStream is)
			throws IOException {
		/**
		 * 写入文件到U盘同理 要获取到UsbFileOutputStream后 通过 f.createNewFile();调用 在U盘中创建文件
		 * 然后获取os后 可以通过输出流将需要写入的文件写到流中即可完成写入操作
		 */
		int bytesRead = 0;
		byte[] buffer = new byte[1024 * 8];
		while ((bytesRead = is.read(buffer)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.flush();
		os.close();
		is.close();
		// ToastTool.showLong(mInstance, "写完文件了");
	}

	/***
	 * 第一次使用软件的时候写入药物列表
	 */
	public void writeYaowulists() {
		// 先看看是不是第一次使用？true 代表不是第一次，false是第一次使用，注意。
		boolean isFirst = SharedpreferenceUtil.getFirstTimeUse(mContext);
		if (!isFirst) {
			// 获取高血压数据。
			StringBuilder sb_gxy = new StringBuilder();
			String[] gxys = getResources().getStringArray(R.array.gxy_yaowu);
			for (String gxy : gxys) {
				sb_gxy.append(gxy);
				sb_gxy.append(SharedpreferenceUtil.YAOWUDATAS_SPLIT);
			}
			String yaowudatas_gxy = sb_gxy.toString();
			if (yaowudatas_gxy.endsWith(SharedpreferenceUtil.YAOWUDATAS_SPLIT)) {
				yaowudatas_gxy = yaowudatas_gxy.substring(0,
						yaowudatas_gxy.length() - 1);
			}
			// 写入高血压的数据
			SharedpreferenceUtil.setYaowuDatas(mContext, yaowudatas_gxy,
					SharedpreferenceUtil.YAOWUDATAS_GXY);
			// 获取糖尿病数据。
			StringBuilder sb_tnb = new StringBuilder();
			String[] tnbs = getResources().getStringArray(R.array.tnb_yaowu);
			for (String tnb : tnbs) {
				sb_tnb.append(tnb);
				sb_tnb.append(SharedpreferenceUtil.YAOWUDATAS_SPLIT);
			}
			String yaowudatas_tnb = sb_tnb.toString();
			if (yaowudatas_tnb.endsWith(SharedpreferenceUtil.YAOWUDATAS_SPLIT)) {
				yaowudatas_tnb = yaowudatas_tnb.substring(0,
						yaowudatas_tnb.length() - 1);
			}
			// 写入糖尿病的数据
			SharedpreferenceUtil.setYaowuDatas(mContext, yaowudatas_tnb,
					SharedpreferenceUtil.YAOWUDATAS_TNB);
			// 设置为不是第一次使用软件了。
			SharedpreferenceUtil.setFirstTimeUse(getApplicationContext(), true);
		}
	}

	/**
	 * 获取正在运行桌面包名（注：存在多个桌面时且未指定默认桌面时，该方法返回Null,使用时需处理这个情况）
	 */
	public static String getLauncherPackageName2(Context context) {
		final Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		final ResolveInfo res = context.getPackageManager().resolveActivity(
				intent, 0);
		if (res.activityInfo == null) {
			// should not happen. A home is always installed, isn't it?
			// 还没有勾选默认的桌面
			System.out.println("没有默认的桌面。需要设置默认的桌面");
			return null;
		}
		if (res.activityInfo.packageName.equals("android")) {
			// 有多个桌面程序存在，且未指定默认项时；
			System.out.println("有多个activity");
			return null;
		} else {
			return res.activityInfo.packageName;
		}
	}

	public static String getOngovId() {
		return SharedpreferenceUtil.getOnGovId(mInstance, "");
	}

	public static String getOnDoctorId() {
		return SharedpreferenceUtil.getOnDoctorId(mInstance, "");
	}

	public static String getOnPwd() {
		return SharedpreferenceUtil.getOnPassword(mInstance, "");
	}

	public static boolean isUserLogin = false;

	public static void setUserLogin(boolean isUserLogin) {
		MyApplication.isUserLogin = isUserLogin;
	}

	public static String getLauncherPackageName(Context context) {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		List<ResolveInfo> resInfoList = context.getPackageManager()
				.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
		if (resInfoList != null) {
			ResolveInfo resInfo;
			for (int i = 0; i < resInfoList.size(); i++) {
				resInfo = resInfoList.get(i);
				if ((resInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
					String mPackageName = resInfo.activityInfo.packageName;
					String mClassName = resInfo.activityInfo.name;
					return mPackageName;
				}
			}
			return null;
		}
		return null;
	}

	public static MyApplication getInstance() {
		return mInstance;
	}

	public static void setUserAndPas(String userName, String password) {
		MyApplication.userName = userName;
		MyApplication.password = password;
	}

	public static String getUserName() {
		return userName;
	}

	public static String getPassword() {
		return password;
	}

	/***
	 * 返回是否已经连接到服务器
	 *
	 * @return true 已连接 false未连接
	 */
	public static boolean isConnected() {
		return isUserLogin && Tools.isNetConnected(getInstance());
		// return Tools.isNetConnected(getInstance())
		// && !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password);
	}

	/***
	 * 设置是否连接的状态。
	 *
	 * @param isConnected
	 */
	public static void setConnected(boolean isConnected) {
		MyApplication.isConnected = isConnected;
	}

	public static Cache getCache() {
		if (mCache == null) {
			mCache = new Cache(mInstance);
		}
		return mCache;
	}
	public void exitApp(){
//		System.exit(0);
//		onTerminate();
//		android.os.Process.killProcess(android.os.Process.myPid());
	}
}
